package sebjul.ecom.dao;

import java.util.*;

import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Singleton;
import javax.persistence.*;


import sebjul.ecom.entities.Article;
import sebjul.ecom.entities.User;

@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class UserDao {
	
	@PersistenceContext
	EntityManager em;
	
	public User createUser(User user) {
		em.persist(user);
		return user;
	}
	
	public User findUserById (int id) {
		return em.find(User.class, id);
	}
	
	public User findByUsername (String username) {
		Query query = em.createNamedQuery("findByUsername");
		query.setParameter("username", username);
		List<User> users = query.getResultList();
		if (users.size()==0)
			return null;
		return users.get(0);
	}
	
	public void deleteUser(User user) {
		em.remove(em.merge(user));
	}
	
	public User updateUser(User user) {
		return em.merge(user);
	}
	public List<User> findUsers() {
		Query query = em.createNamedQuery("findAllUsers");
		return query.getResultList();
	}
	
}
